<template>
  <div class="py-16 md:py-24 bg-gradient-to-b from-white to-neutral/20 min-h-screen">
    <div class="container mx-auto px-4">
      <!-- 页面标题区 -->
      <div class="mb-12 scroll-animate">
        <div
          class="inline-block px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full mb-4"
        >
          分类浏览
        </div>
        <h2 class="text-[clamp(1.8rem,4vw,2.8rem)] font-bold text-primary mb-3 leading-tight">
          拍品分类
        </h2>
        <p class="text-gray-600 max-w-2xl text-lg">
          探索各类艺术品分类，从传统书画到现代珠宝，找到您心仪的收藏珍品
        </p>
      </div>

      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧分类导航 -->
        <div class="lg:w-1/4 scroll-animate" style="animation-delay: 0.1s">
          <div class="bg-white rounded-xl shadow-md p-6 sticky top-24">
            <h3 class="font-bold text-lg text-primary mb-5 pb-3 border-b border-gray-100">
              全部分类
            </h3>

            <ul class="space-y-1">
              <li v-for="(category, index) in allCategories" :key="category.id">
                <button
                  class="category-item w-full flex items-center justify-between p-3 rounded-lg transition-all duration-200"
                  :class="{
                    'bg-primary/10 text-primary font-medium': selectedCategoryId === category.id,
                  }"
                  @click="handleCategoryClick(category.id)"
                >
                  <div class="flex items-center">
                    <i :class="category.icon" class="mr-3 text-lg"></i>
                    <span>{{ category.name }}</span>
                  </div>
                  <span class="bg-gray-100 text-gray-600 text-xs px-2 py-1 rounded-full">
                    {{ category.count }}
                  </span>
                </button>
              </li>
            </ul>

            <!-- 年代筛选 -->
            <div class="mt-8">
              <h4 class="font-medium text-gray-800 mb-4">年代筛选</h4>
              <div class="space-y-2">
                <label class="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-primary rounded border-gray-300"
                    v-model="selectedEras"
                    :value="'ancient'"
                  />
                  <span class="ml-2 text-gray-700">古代 ({{ eraCounts.ancient }})</span>
                </label>
                <label class="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-primary rounded border-gray-300"
                    v-model="selectedEras"
                    :value="'modern'"
                  />
                  <span class="ml-2 text-gray-700">近现代 ({{ eraCounts.modern }})</span>
                </label>
                <label class="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-primary rounded border-gray-300"
                    v-model="selectedEras"
                    :value="'contemporary'"
                  />
                  <span class="ml-2 text-gray-700">当代 ({{ eraCounts.contemporary }})</span>
                </label>
              </div>
            </div>

            <!-- 价格区间筛选 -->
            <div class="mt-8">
              <h4 class="font-medium text-gray-800 mb-4">价格区间</h4>
              <div class="space-y-2">
                <label class="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-primary rounded border-gray-300"
                    v-model="selectedPriceRanges"
                    :value="'0-10'"
                  />
                  <span class="ml-2 text-gray-700">10万以下</span>
                </label>
                <label class="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-primary rounded border-gray-300"
                    v-model="selectedPriceRanges"
                    :value="'10-50'"
                  />
                  <span class="ml-2 text-gray-700">10-50万</span>
                </label>
                <label class="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-primary rounded border-gray-300"
                    v-model="selectedPriceRanges"
                    :value="'50-100'"
                  />
                  <span class="ml-2 text-gray-700">50-100万</span>
                </label>
                <label class="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-primary rounded border-gray-300"
                    v-model="selectedPriceRanges"
                    :value="'100-500'"
                  />
                  <span class="ml-2 text-gray-700">100-500万</span>
                </label>
                <label class="flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    class="form-checkbox h-4 w-4 text-primary rounded border-gray-300"
                    v-model="selectedPriceRanges"
                    :value="'500+'"
                  />
                  <span class="ml-2 text-gray-700">500万以上</span>
                </label>
              </div>
            </div>

            <!-- 筛选重置 -->
            <button
              class="mt-8 w-full py-2 border border-gray-200 rounded-lg text-gray-600 hover:bg-gray-50 transition-colors"
              @click="resetFilters"
            >
              重置筛选条件
            </button>
          </div>
        </div>

        <!-- 右侧分类内容区 -->
        <div class="lg:w-3/4">
          <!-- 分类详情头部 -->
          <div
            class="bg-white rounded-xl shadow-md p-6 mb-8 scroll-animate"
            style="animation-delay: 0.2s"
          >
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div>
                <h3 class="text-2xl font-bold text-primary mb-2">
                  {{ currentCategory?.name || '全部拍品' }}
                </h3>
                <p class="text-gray-600">
                  {{ currentCategory?.description || '浏览所有类别的精选拍品，找到您心仪的收藏' }}
                </p>
              </div>

              <el-select
                v-model="sortType"
                placeholder="排序方式"
                class="w-[180px] custom-select"
                size="default"
              >
                <el-option value="recommend" label="推荐排序" />
                <el-option value="price-asc" label="价格从低到高" />
                <el-option value="price-desc" label="价格从高到低" />
                <el-option value="newest" label="最新上架" />
              </el-select>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="flex justify-center items-center py-20">
            <el-loading-spinner class="text-primary" />
          </div>

          <!-- 分类拍品网格 -->
          <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            <div
              v-for="(item, index) in filteredItems"
              :key="item.id"
              class="group bg-white rounded-xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1 scroll-animate"
              :style="{ animationDelay: `${(index % 6) * 0.1}s` }"
            >
              <!-- 拍品图片 -->
              <div class="relative overflow-hidden aspect-[3/4]">
                <img
                  :src="item.image"
                  :alt="item.name"
                  class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
                />
                <!-- 标签 -->
                <div class="absolute top-3 left-3">
                  <span
                    class="inline-block bg-primary text-white text-xs font-bold px-2 py-1 rounded-md"
                  >
                    {{ item.era }}
                  </span>
                </div>
                <!-- 收藏按钮 -->
                <button
                  class="absolute top-3 right-3 w-8 h-8 bg-white/80 backdrop-blur-sm rounded-full flex items-center justify-center text-gray-600 hover:text-red-500 transition-colors"
                  @click.stop="toggleFavorite(item.id)"
                >
                  <i :class="item.isFavorite ? 'fa fa-heart text-red-500' : 'fa fa-heart-o'"></i>
                </button>
              </div>

              <!-- 拍品信息 -->
              <div class="p-5">
                <h3
                  class="font-bold text-lg text-primary mb-2 group-hover:text-primary-dark transition-colors line-clamp-1"
                >
                  {{ item.name }}
                </h3>
                <p class="text-gray-600 text-sm mb-4 line-clamp-2 h-12">
                  {{ item.description }}
                </p>
                <div class="flex justify-between items-center">
                  <div>
                    <div class="text-xs text-gray-500 mb-1">起拍价</div>
                    <div class="text-primary font-bold text-xl">
                      ¥{{ item.startingPrice.toLocaleString() }}
                    </div>
                  </div>
                  <router-link
                    :to="`/item/${item.id}`"
                    class="text-primary hover:text-primary-dark font-medium flex items-center gap-1 transition-colors"
                  >
                    <span>详情</span>
                    <i class="fa fa-arrow-right text-sm"></i>
                  </router-link>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div
            v-if="filteredItems.length === 0 && !isLoading"
            class="text-center py-16 bg-white rounded-xl shadow-md mt-6"
          >
            <i class="fa fa-search text-4xl text-gray-300 mb-4"></i>
            <h3 class="text-xl font-medium text-gray-700 mb-2">未找到符合条件的拍品</h3>
            <p class="text-gray-500 mb-6">请尝试调整筛选条件或浏览其他分类</p>
            <button
              class="bg-primary text-white font-medium px-6 py-2 rounded-lg hover:bg-primary-dark transition-colors"
              @click="resetFilters"
            >
              重置筛选条件
            </button>
          </div>

          <!-- 加载更多 -->
          <div
            v-if="filteredItems.length > 0 && !isLoading"
            class="text-center mt-12 scroll-animate"
          >
            <button
              class="bg-white border border-primary text-primary hover:bg-primary hover:text-white font-medium px-8 py-3 rounded-lg transition-all duration-300 flex items-center gap-2 mx-auto"
              @click="loadMore"
              :disabled="isLoadingMore"
            >
              <span>{{ isLoadingMore ? '加载中...' : '加载更多拍品' }}</span>
              <i class="fa fa-refresh" :class="{ 'fa-spin': isLoadingMore }"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage, ElSelect, ElOption, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'

// 定义分类类型
interface Category {
  id: number
  name: string
  icon: string
  count: number
  description: string
}

// 定义拍品类型
interface ProductItem {
  id: number
  name: string
  image: string
  categoryId: number
  era: '古代' | '近现代' | '当代' // 明确限定为这三个值
  description: string
  startingPrice: number
  isFavorite: boolean
  addedTime: string
}

// 定义分类配置类型 - 修复类型定义
interface CategoryConfig {
  namePrefix: string[]
  artists?: string[]
  materials?: string[]
  dynasties?: string[]
  calligraphers?: string[]
  eraOptions: Array<'古代' | '近现代' | '当代'>
  priceRange: [number, number]
}

// 分类数据 - 完善各类别数据
const allCategories: Category[] = [
  {
    id: 0,
    name: '全部拍品',
    icon: 'fa-th-large',
    count: 128,
    description: '浏览所有类别的精选拍品，包括书画、玉器、瓷器、珠宝等多个品类',
  },
  {
    id: 1,
    name: '书画作品',
    icon: 'fa-paint-brush',
    count: 36,
    description: '包含中国传统绘画和书法作品，从古代到现代的名家之作',
  },
  {
    id: 2,
    name: '玉器翡翠',
    icon: 'fa-diamond',
    count: 28,
    description: '精选和田玉、翡翠等各类玉器，工艺精湛，具有较高收藏价值',
  },
  {
    id: 3,
    name: '瓷器杂项',
    icon: 'fa-vase',
    count: 31,
    description: '涵盖青瓷、白瓷、彩瓷等各类瓷器，以及文房四宝等杂项艺术品',
  },
  {
    id: 4,
    name: '珠宝钟表',
    icon: 'fa-clock-o',
    count: 15,
    description: '名贵珠宝首饰和古董钟表，兼具装饰价值和收藏价值',
  },
  {
    id: 5,
    name: '书法作品',
    icon: 'fa-pencil',
    count: 18,
    description: '历代书法名家真迹或精品摹本，包括楷书、行书、草书等多种字体',
  },
]

// 年代数量统计
const eraCounts = {
  ancient: 42,
  modern: 56,
  contemporary: 30,
}

// 状态管理
const selectedCategoryId = ref(0)
const selectedEras = ref<string[]>([])
const selectedPriceRanges = ref<string[]>([])
const sortType = ref<'recommend' | 'price-asc' | 'price-desc' | 'newest'>('recommend')
const isLoading = ref(false)
const isLoadingMore = ref(false)
const router = useRouter()

// 生成指定范围内的随机整数
const getRandomInt = (min: number, max: number): number => {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

// 生成模拟日期
const getRandomDate = (): string => {
  const start = new Date(2023, 0, 1)
  const end = new Date()
  const randomDate = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
  return randomDate.toISOString().split('T')[0] ?? ''
}

// 分类配置 - 使用明确的类型定义
const categoriesConfig: Record<number, CategoryConfig> = {
  1: {
    namePrefix: ['山水', '花鸟', '人物', '风景'],
    artists: ['张大千', '齐白石', '徐悲鸿', '黄宾虹', '傅抱石'],
    eraOptions: ['古代', '近现代', '当代'],
    priceRange: [500000, 5000000],
  },
  2: {
    namePrefix: ['玉璧', '玉佩', '玉壶', '玉如意', '玉摆件'],
    materials: ['和田玉', '翡翠', '白玉', '青玉', '碧玉'],
    eraOptions: ['古代', '近现代'],
    priceRange: [300000, 3000000],
  },
  3: {
    namePrefix: ['青花瓷', '青瓷', '白瓷', '彩瓷', '铜炉'],
    dynasties: ['宋', '元', '明', '清'],
    eraOptions: ['古代', '近现代'],
    priceRange: [800000, 6000000],
  },
  4: {
    namePrefix: ['项链', '手镯', '戒指', '腕表', '耳环'],
    materials: ['黄金', '白金', '钻石', '翡翠', '红宝石'],
    eraOptions: ['近现代', '当代'],
    priceRange: [100000, 2000000],
  },
  5: {
    namePrefix: ['对联', '条幅', '横批', '手卷', '册页'],
    calligraphers: ['王羲之', '颜真卿', '柳公权', '米芾', '启功'],
    eraOptions: ['古代', '近现代', '当代'],
    priceRange: [200000, 4000000],
  },
}

// 为每个分类生成特定的模拟拍品数据
const generateCategoryItems = (
  categoryId: number,
  count: number,
  startId: number
): ProductItem[] => {
  // 通用描述
  const descriptions = [
    '工艺精湛，保存完好，具有较高的艺术价值和收藏价值',
    '材质优良，做工精细，是该类别的代表性作品',
    '经专家鉴定为真品，流传有序，来源可靠',
    '品相完好，细节精美，体现了当时的工艺水平',
    '罕见珍品，市场上难得一见，升值空间巨大',
  ]

  // 获取当前分类的配置
  const config = categoryId === 0 ? null : categoriesConfig[categoryId]

  return Array.from({ length: count }, (_, i) => {
    let name = ''
    let era: '古代' | '近现代' | '当代' = '当代' // 明确类型

    if (categoryId === 0) {
      // 全部拍品 - 随机选择一个分类的风格
      const randomCat = getRandomInt(1, 5) as keyof typeof categoriesConfig
      const randomConfig = categoriesConfig[randomCat] as any
      const prefix = randomConfig.namePrefix[getRandomInt(0, randomConfig.namePrefix.length - 1)]

      // 确定艺术家或朝代信息
      let creator = ''
      if (randomConfig.artists) {
        creator = randomConfig.artists[getRandomInt(0, randomConfig.artists.length - 1)]
      } else if (randomConfig.dynasties) {
        creator = randomConfig.dynasties[getRandomInt(0, randomConfig.dynasties.length - 1)]
      } else if (randomConfig.calligraphers) {
        creator = randomConfig.calligraphers[getRandomInt(0, randomConfig.calligraphers.length - 1)]
      } else if (randomConfig.materials) {
        creator = randomConfig.materials[getRandomInt(0, randomConfig.materials.length - 1)]
      }

      name = `${creator} ${prefix}图`
      era = randomConfig.eraOptions[getRandomInt(0, randomConfig.eraOptions.length - 1)] as
        | '古代'
        | '近现代'
        | '当代'
    } else if (config) {
      // 特定分类
      const prefix = config.namePrefix[getRandomInt(0, config.namePrefix.length - 1)]

      // 确定创作者/材质/朝代
      let creator: any = ''
      if (config.artists) {
        creator = config.artists[getRandomInt(0, config.artists.length - 1)]
      } else if (config.dynasties) {
        creator = config.dynasties[getRandomInt(0, config.dynasties.length - 1)]
      } else if (config.calligraphers) {
        creator = config.calligraphers[getRandomInt(0, config.calligraphers.length - 1)]
      } else if (config.materials) {
        creator = config.materials[getRandomInt(0, config.materials.length - 1)]
      }

      name = `${creator} ${prefix}`
      era = config.eraOptions[getRandomInt(0, config.eraOptions.length - 1)] as
        | '古代'
        | '近现代'
        | '当代'
    } else {
      name = `拍品${startId + i}`
      era = ['古代', '近现代', '当代'][getRandomInt(0, 2)] as '古代' | '近现代' | '当代'
    }

    const priceRange = config ? config.priceRange : [100000, 6000000]
    const minPrice = priceRange?.[0] ?? 100000
    const maxPrice = priceRange?.[1] ?? 6000000

    return {
      id: startId + i,
      name,
      image: `https://picsum.photos/id/${((startId + i) % 100) + 100}/600/800`,
      categoryId,
      era,
      description: descriptions[getRandomInt(0, descriptions.length - 1)] ?? '',
      startingPrice: getRandomInt(minPrice, maxPrice),
      isFavorite: false,
      addedTime: getRandomDate(),
    }
  })
}

// 生成所有分类的模拟数据
const allItems = ref<ProductItem[]>([])
const initAllItems = () => {
  let startId = 1
  // 为每个分类生成对应数量的拍品
  allCategories.forEach((category) => {
    if (category.id > 0) {
      // 跳过全部拍品
      const items = generateCategoryItems(category.id, category.count, startId)
      allItems.value.push(...items)
      startId += category.count
    }
  })
}

// 初始化数据
initAllItems()

// 当前显示的拍品
const displayItems = ref<ProductItem[]>([...allItems.value.slice(0, 12)])

// 处理分类点击
const handleCategoryClick = (id: number) => {
  // 仅在需要时才滚动
  const shouldScroll = window.scrollY > 300 // 当滚动超过300px时才滚动到顶部
  selectedCategoryId.value = id

  // 重置筛选条件但保留分类选择
  selectedEras.value = []
  selectedPriceRanges.value = []

  // 显示加载状态
  isLoading.value = true

  // 短暂延迟模拟数据加载
  setTimeout(() => {
    // 根据分类筛选数据
    const filtered = allItems.value.filter((item) => id === 0 || item.categoryId === id)
    displayItems.value = filtered.slice(0, 12)
    isLoading.value = false

    // 如果需要，滚动到顶部
    if (shouldScroll) {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
  }, 300)
}

// 切换收藏状态
const toggleFavorite = (id: number) => {
  const item = displayItems.value.find((item) => item.id === id)
  if (item) {
    item.isFavorite = !item.isFavorite
    ElMessage({
      message: item.isFavorite ? '已添加到收藏' : '已从收藏中移除',
      type: 'success',
      duration: 1500,
    })
  }
}

// 重置筛选条件
const resetFilters = () => {
  selectedEras.value = []
  selectedPriceRanges.value = []
  sortType.value = 'recommend'
}

// 加载更多
const loadMore = () => {
  if (isLoadingMore.value) return

  isLoadingMore.value = true

  // 模拟接口请求延迟
  setTimeout(() => {
    // 获取当前筛选条件下的所有符合条件的拍品
    const allFiltered = allItems.value.filter(
      (item) =>
        (selectedCategoryId.value === 0 || item.categoryId === selectedCategoryId.value) &&
        (selectedEras.value.length === 0 ||
          selectedEras.value.includes(
            item.era === '古代' ? 'ancient' : item.era === '近现代' ? 'modern' : 'contemporary'
          ))
    )

    // 计算还需要加载多少
    const remaining = allFiltered.filter(
      (item) => !displayItems.value.some((d) => d.id === item.id)
    )

    // 添加新数据
    if (remaining.length > 0) {
      displayItems.value = [...displayItems.value, ...remaining.slice(0, 6)]
    } else {
      ElMessage({
        message: '没有更多拍品了',
        type: 'info',
        duration: 1500,
      })
    }

    isLoadingMore.value = false
  }, 1000)
}

// 当前选中的分类
const currentCategory = computed(() => {
  return allCategories.find((cat) => cat.id === selectedCategoryId.value)
})

// 根据筛选条件过滤拍品
const filteredItems = computed<ProductItem[]>(() => {
  // 基础筛选
  let result = [...displayItems.value]

  // 按年代筛选
  if (selectedEras.value.length > 0) {
    result = result.filter((item) =>
      selectedEras.value.includes(
        item.era === '古代' ? 'ancient' : item.era === '近现代' ? 'modern' : 'contemporary'
      )
    )
  }

  // 按价格区间筛选
  if (selectedPriceRanges.value.length > 0) {
    result = result.filter((item) => {
      const price = item.startingPrice / 10000 // 转换为万元
      return selectedPriceRanges.value.some((range) => {
        switch (range) {
          case '0-10':
            return price < 10
          case '10-50':
            return price >= 10 && price < 50
          case '50-100':
            return price >= 50 && price < 100
          case '100-500':
            return price >= 100 && price < 500
          case '500+':
            return price >= 500
          default:
            return false
        }
      })
    })
  }

  // 排序
  switch (sortType.value) {
    case 'price-asc':
      return result.sort((a, b) => a.startingPrice - b.startingPrice)
    case 'price-desc':
      return result.sort((a, b) => b.startingPrice - a.startingPrice)
    case 'newest':
      return result.sort(
        (a, b) => new Date(b.addedTime).getTime() - new Date(a.addedTime).getTime()
      )
    default:
      return result // 推荐排序（默认顺序）
  }
})

// 滚动动画初始化
onMounted(() => {
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('animate-in')
          observer.unobserve(entry.target)
        }
      })
    },
    { threshold: 0.1 }
  )

  document.querySelectorAll('.scroll-animate').forEach((el) => {
    observer.observe(el)
  })
})

onUnmounted(() => {
  // 清理工作
})
</script>

<style scoped>
/* 滚动入场动画 */
.scroll-animate {
  opacity: 0;
  transform: translateY(30px);
  transition: opacity 0.6s ease, transform 0.6s ease;
}

.scroll-animate.animate-in {
  opacity: 1;
  transform: translateY(0);
}

/* 分类项样式 */
.category-item {
  text-align: left;
}

.category-item:hover {
  background-color: rgba(26, 54, 93, 0.05);
}

/* 自定义Element Select样式 */
:deep(.custom-select .el-select__wrapper) {
  border-radius: 8px;
  border-color: #e2e8f0;
  padding: 2px 12px;
  height: 40px;
}

:deep(.custom-select .el-select__placeholder) {
  color: #94a3b8;
}

:deep(.custom-select .el-select__input) {
  color: #1a365d;
}

:deep(.custom-select .el-select__arrow) {
  color: #1a365d;
}

:deep(.custom-select .el-select-dropdown__item) {
  color: #1a365d;
}

:deep(.custom-select .el-select-dropdown__item:hover) {
  background-color: rgba(26, 54, 93, 0.08);
}

:deep(.custom-select .el-select-dropdown__item.selected) {
  color: #1a365d;
  background-color: rgba(26, 54, 93, 0.05);
}

/* 自定义颜色变量 */
:root {
  --primary: #1a365d;
  --primary-dark: #0f243b;
  --primary-light: #2c4a70;
}

.text-primary {
  color: var(--primary);
}

.text-primary-dark {
  color: var(--primary-dark);
}

.bg-primary {
  background-color: var(--primary);
}

.bg-primary-dark {
  background-color: var(--primary-dark);
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .lg\:w-1\/4,
  .lg\:w-3\/4 {
    width: 100%;
  }
}
</style>
